package com.webex.ta.hydra.function;

import com.webex.ta.hydra.core.Keyword;
import com.webex.ta.hydra.exceptions.InvalidVariableException;
import com.webex.ta.hydra.util.ClassFinder;
import com.webex.ta.hydra.util.HydraUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: vegaz
 * Date: 2010-8-30
 * Time: 13:38:43
 * To change this template use File | Settings | File Templates.
 */
public class FunctionManager {
    private static Map<String, Class> functions = new HashMap<String, Class>();

    static {
        try {
            List<String> functionClasses = ClassFinder.findClassesThatExtend(HydraUtils.getCorePaths(), new Class[] {
                        Function.class});
            for (String functionClass : functionClasses) {
                Class cl = Class.forName(functionClass);
                String referenceKey = ((Function) cl.newInstance()).getReferenceKey();
                functions.put(referenceKey, cl);
            }
        } catch (Exception e) {

        }
    }

    public static Object getNamedFunction(String functionName) throws InvalidVariableException {
        if (functions.containsKey(functionName)) {
			try {
				return (Function)(functions.get(functionName)).newInstance();
			} catch (Exception e) {
				throw new InvalidVariableException();
			}
		}
		return new SimpleVariable(functionName);
    }
}
